/*
 * @Author: jianfanfan 1217572833@qq.com
 * @Date: 2025-04-07 17:27:30
 * @LastEditors: jianfanfan 1217572833@qq.com
 * @LastEditTime: 2025-04-14 17:13:45
 * @FilePath: \chinese-forum\lib\api.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios';

// 创建 axios 实例
const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 在这里可以添加 token 等认证信息
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    console.error('请求配置错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    
    return response.data;
  },
  (error) => {
    // 统一错误处理
    if (error.response) {   
      // 根据状态码处理错误
      switch (error.response.status) {
        case 400:
          // 请求参数错误
          console.error('请求参数错误:', error.response.data);
          break;
        case 401:
          // 未授权，可以跳转到登录页
          window.location.href = '/login';
          break;
        case 403:
          // 权限不足
          console.error('权限不足');
          break;
        case 404:
          // 资源不存在
          console.error('请求的资源不存在');
          break;
        case 500:
          // 服务器错误
          console.error('服务器错误');
          break;
        default:
          console.error('请求错误:', error.message);
      }
    } else if (error.request) {
      console.error('No response received:', error.request);
    } else {
      console.error('Error setting up request:', error.message);
    }
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export const get = async <T>(url: string, params?: any): Promise<T> => {
  try {
    const response = await api.get<T>(url, { params });
    return response;
  } catch (error) {
    throw error;
  }
};

// 封装 POST 请求
export const post = async <T>(url: string, data?: any): Promise<T> => {
  try {
    const response = await api.post<T>(url, data);
    return response;
  } catch (error) {
    throw error;
  }
};

// 封装 PUT 请求
export const put = async <T>(url: string, data?: any): Promise<T> => {
  try {
    const response = await api.put<T>(url, data);
    return response;
  } catch (error) {
    throw error;
  }
};

// 封装 DELETE 请求
export const del = async <T>(url: string): Promise<T> => {
  try {
    const response = await api.delete<T>(url);
    return response;
  } catch (error) {
    throw error;
  }
};
export default api;